package com.example.demo.websocket;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * websocket 测试：服务器端 创建websocket客户端，发送消息给客户端（浏览器）
 * @author Administrator
 *
 */

public class WebSocketTest {

	public static void main(String[] args){
        // timer jdk自带定时器
       Timer timer = new Timer();  
       timer.schedule(new MyTask(), 1000, 5000);	//1秒之后开始，5秒一次
   }
   static int num = 0;
   static class MyTask extends TimerTask {  

       @Override  
       public void run() {
    	   try {
	    	   JSONObject json=new JSONObject();
	    	   json.put("deptno", "1");
	    	   json.put("dname", "sale");
	    	   json.put("loc", "beijing");
	    	   
	    	   WebSocketClient client = new WebSocketClient();
	           String uri = "ws://localhost:8008/websocket";
	           client.start(uri);
           
               num++;
//               client.sendMessage("消息测试"+num);
               client.sendMessage(json.toString());
               client.closeSocket();
               System.out.println(num);
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           } catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

       }  

   } 
	
}
